package hdelos

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"the-assistant-of-sa/cache"
	"the-assistant-of-sa/models"
	"the-assistant-of-sa/pkg"
	"time"
)

func Dl(c *gin.Context) {
	name := c.PostForm("name")
	passes := c.PostForm("passes")

	var user models.User
	err := models.DB.Where("name=?", name).First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户查询失败",
		})
		return
	}
	if user.Name == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户不存在",
		})
		return
	}
	if user.Passes != pkg.Mds(passes) {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"data": user,
	})
	return
}
func Add(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	are := c.PostForm("are")

	if title == "" || content == "" || are == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	data := models.Ares{
		Title:   title,
		Content: content,
		Are:     are,
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "发布失败",
		})
		return
	}
	redis_key := "redis_id" + strconv.Itoa(int(data.ID))
	var user models.Ares
	models.DB.Where("id=?", data.ID).First(&user)
	jsonAdd, _ := json.Marshal(user)
	cache.Rdb.Set(cache.Ctx, redis_key, jsonAdd, time.Hour*2)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "发布成功",
	})
	return
}
func Xq(c *gin.Context) {
	id := c.Query("id")
	var are models.Ares
	err := models.DB.Where("id=?", id).First(&are).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": are,
	})
	return
}
func Del(c *gin.Context) {
	id := c.Query("id")
	err := models.DB.Where("id=?", id).Delete(&models.Ares{}).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "删除失败",
		})
		return
	}
	redis_key := "redis_id" + id
	cache.Rdb.Del(cache.Ctx, redis_key)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
	return
}

func List(c *gin.Context) {
	var po []models.Ares

	redis_key := "redis_liat"
	pos, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if pos == "" {
		models.DB.Find(&po)
		jsonList, _ := json.Marshal(po)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonList, time.Hour*2)
	} else {
		json.Unmarshal([]byte(pos), &po)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": po,
	})
	return
}
